package com.myway.service.impl;

import com.github.pagehelper.PageHelper;
import com.myway.dao.*;
import com.myway.dto.common.JsonData;
import com.myway.dto.common.ResultEntity;
import com.myway.dto.order.domain.OrderStatus;
import com.myway.dto.param.OrderParam;
import com.myway.dto.util.OrderNumberGenerator;
import com.myway.dto.util.PageUtil;
import com.myway.dto.vo.FlyOrderDetailsVo;
import com.myway.dto.vo.FlyPassengeDetailsVo;
import com.myway.dto.vo.FlySegmentVo;
import com.myway.dto.vo.FlyTicketVo;
import com.myway.pojo.*;
import com.myway.service.IntegralService;
import com.myway.service.OrderService;
import com.myway.service.TicketService;
import com.myway.service.ibe.command.PNRCommand;
import com.myway.service.payment.Oceanpayment.TBCPayService;
import com.myway.utils.eamil.EmailUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * @Author: mashuai
 * @Date: 2018/8/13 18:38
 * @Version 1.0
 */
@Service
@Slf4j
public class OrderServiceImpl implements OrderService {
    @Autowired
    private FlyOrderMapper flyOrderMapper;
    @Autowired
    private FlyPassengeMapper flyPassengeMapper;
    @Autowired
    private FlyTicketMapper flyTicketMapper;
    @Autowired
    private TabCityMapper tabCityMapper;
    @Autowired
    private FlySegmentMapper flySegmentMapper;
    @Autowired
    private FlyPassengerSegmentMapper flyPassengerSegmentMapper;
    @Autowired
    private FlyOrderPaymentMapper flyOrderPaymentMapper;
    @Autowired
    private PaymentMapper paymentMapper;
    @Autowired
    private TabAirportManageMapper tabAirportManageMapper;
    @Autowired
    private FlyPnrMapper flyPnrMapper;
    @Autowired
    private MyTabMemberInfoMapper myTabMemberInfoMapper;
    @Autowired
    private FlyRefundReversalMapper flyRefundReversalMapper;
    @Autowired
    private FlyRefundOptionMapper flyRefundOptionMapper;
    @Autowired
    private PNRCommand pnrCommand;

    @Autowired
    private TicketService ticketService;

    @Autowired
    private TBCPayService tbcPayService;

    @Autowired
    private IntegralService integralService;


    @Override
    public void closeOrder() {
        List<FlyOrder> orders = flyOrderMapper.getFlyOrderByTout();
        for (FlyOrder order : orders) {
            order.setOrderStatus(OrderStatus.XX.toString());
            updateByPrimaryKeySelective(order);
        }
    }

    @Override
    public JsonData selectByOrderId(String orderId) {
        if (orderId != null && orderId != "") {
            FlyOrder flyOrder = flyOrderMapper.getFlyOrderById(orderId);
            return JsonData.success(flyOrder);
        } else {
            return JsonData.fail("订单编号为空");
        }

    }

    /**
     * 条件查询机票订单
     *
     * @param param
     * @return
     */
    @Override
    public JsonData selectByManyInf(OrderParam param) {
        JsonData jsonData = new JsonData(true);
        /*System.out.println("参数：" + param);*/
        String userId = param.getUserId();
        if (userId != null && userId != "") {
            int pages = param.getPageIndex();// 当前页
            int rows = param.getPageSize();// 每页条数
            int startNumber = (pages - 1) * rows;// 每页起始条数
            param.setPageIndex(startNumber);
            param.setPageSize(rows);
            //查询总数
            int total = flyOrderMapper.countSearch(param);
            Map<String, Object> result = new HashMap<String, Object>();
            if (total > 0) {
                List<FlyOrder> flyOrders = flyOrderMapper.selectByManyInf(param);
                result.put("data", flyOrders);
                result.put("totalCount", total);
                result.put("page", pages);
                result.put("limit", rows);
                jsonData.setData(result);
                jsonData.setMsg("SUCCESS");
            }
            if (total == 0) {
                jsonData.setMsg("NODATA");
            }
        }
        if (userId == null || userId == "") {
            jsonData.setMsg("用户id不能为空！");
        }
        return jsonData;
    }


    @Override
    public JsonData appSelectOrderByParam(OrderParam param) {
        String userId = param.getUserId();
        if (userId == null || userId == "") {
            return JsonData.fail("The user id cannot be empty");
        }
        int currentPage = PageUtil.getCurrentPage(param.getTotal(),6);
        PageHelper.startPage(currentPage, 6);
        String orderStatus = param.getOrderStatus();
        if(!StringUtils.isEmpty(orderStatus)){
            String orderStatusPJ="";
            String[] orderStatusArr = orderStatus.split(",");
            for (int i = 0; i <orderStatusArr.length ; i++) {
                String orderStatusStr = orderStatusArr[i];
                orderStatusPJ+="'"+orderStatusStr+"',";
            }
            if(orderStatusPJ.length()>0){
                orderStatusPJ=orderStatusPJ.substring(0,orderStatusPJ.length()-1);
                param.setOrderStatus(orderStatusPJ);
            }
        }

        List<FlyOrder> FlyOrderList = flyOrderMapper.appSelectOrderByParam(param);
        return JsonData.success(FlyOrderList,"select success");
    }
    /**
     * 统计机票订单
     *
     * @param param
     * @return
     */
    @Override
    public JsonData countSearch(OrderParam param) {
        if (param == null) {
            return JsonData.fail("统计错误，参数不能为空！");
        } else {
            int total = flyOrderMapper.countSearch(param);
            return JsonData.success(total, "success!");
        }
    }

    /**
     * 添加机票订单
     *
     * @param flyOrder
     * @return
     */
    @Override
    public JsonData insertSelective(FlyOrder flyOrder) {
        flyOrder.setId(OrderNumberGenerator.getOrderNo());
        flyOrder.setOrderId(String.valueOf(OrderNumberGenerator.getOrderNo()));
        flyOrder.setOrderStatus(OrderStatus.WK.toString());
        flyOrderMapper.insertSelective(flyOrder);
        return JsonData.success();
    }

    /**
     * 根据订单id删除订单
     *
     * @param flyOrder
     * @return
     */
    @Override
    public JsonData deleteByPrimaryKey(FlyOrder flyOrder) {
        if (flyOrder.getId() != null) {
            flyOrderMapper.deleteByPrimaryKey(flyOrder.getId());
            return JsonData.success();
        } else {
            return JsonData.fail("删除失败，订单id不能为空！");
        }
    }

    /**
     * 修改机票订单
     *
     * @param flyOrder
     * @return
     */
    @Override
    public JsonData updateByPrimaryKeySelective(FlyOrder flyOrder) {
        if (flyOrder.getId() != null) {
            if (flyOrder.getOrderStatus() != null && flyOrder.getOrderStatus().equals(OrderStatus.XX.toString())) {
                List<FlyPnr> flyPnrs = flyPnrMapper.getPnrOrderId(String.valueOf(flyOrder.getId()));
                try {
                    for (FlyPnr flyPnr : flyPnrs) {
                        boolean flag = pnrCommand.pnrExist(flyPnr.getPnrNo());
                        if (flag) {
                            boolean flag1 = pnrCommand.isTicket(flyPnr.getPnrNo());
                            if (!flag1) return JsonData.fail("已出票");
                            pnrCommand.cancelPnr(flyPnr.getPnrNo());    // 一个订单下pnr出票状态一致
                        }
                    }
                    /*for (FlyPnr flyPnr: flyPnrs) {
                        boolean flag = pnrCommand.pnrExist(flyPnr.getPnrNo());
                        if(flag)
                            pnrCommand.cancelPnr(flyPnr.getPnrNo());
                    }*/
                } catch (Exception e) {
                    return JsonData.fail("取消PNR失败！");
                }
            }
            flyOrderMapper.updateByPrimaryKeySelective(flyOrder);
            return JsonData.success();
        } else {
            return JsonData.fail("修改订单失败！");
        }
    }

    /**
     * @return com.myway.dto.common.JsonData
     * @Author MaShuai
     * @Description 根据订单号查询订单详情信息(乘客、总价、航段等信息)
     * @Date 2018/8/21 16:33
     * @Param orderId
     **/
    @Override
    public JsonData selectOrderDetailsByOrderId(String orderId) {

        if (orderId != null && !"".equals(orderId)) {
            //初始化订单详情
            FlyOrderDetailsVo flyOrderDetailsVo = new FlyOrderDetailsVo();
            // 根据订单号查询出订单表信息
            FlyOrder flyOrder = flyOrderMapper.getFlyOrderById(orderId);
            List<FlySegment> flySegmentList = flySegmentMapper.getFlySegmentListByOrderId(flyOrder.getId());

            List<FlyPassengeDetailsVo> flyPassengeDetailsVoList = getFlyPassengeDetailsVoList(flyOrder.getId());
            List<FlyTicketVo> flyTicketVoList = flyTicketMapper.selectVoByPrimaryKey(flyOrder.getId());
            List<Payment> paymentList = getPayment(orderId);

            flyOrderDetailsVo.setFlyOrder(flyOrder);
            flyOrderDetailsVo.setFlySegments(flySegmentList);
            flyOrderDetailsVo.setFlyPassengeDetailsVos(flyPassengeDetailsVoList);
            flyOrderDetailsVo.setFlyTicketVos(flyTicketVoList);
            if(paymentList!=null&&paymentList.size()>0){
                flyOrderDetailsVo.setPayment(paymentList.get(0));
            }
            return JsonData.success(flyOrderDetailsVo, "SUCCESS");
        } else {
            return JsonData.fail("Order details query failed, order number shall not be empty!");
        }

    }

    private List<FlyPassengeDetailsVo> getFlyPassengeDetailsVoList(Long order_id) {

        List<FlyPassengeDetailsVo> flyPassengeDetailsVoList = new ArrayList<>();

        FlyPnr flyPnr;
        List<FlyPassengerSegment> flyPassengerSegmentList;

        List<FlyPassenge> flyPassengeList = flyPassengeMapper.getFlyPassengeByOrderId(String.valueOf(order_id));
        for (FlyPassenge flyPassenge : flyPassengeList) {
            FlyPassengeDetailsVo flyPassengeDetailsVo = new FlyPassengeDetailsVo();
            flyPnr = flyPnrMapper.selectByPrimaryKey(flyPassenge.getPnrId());
            flyPassengeDetailsVo.setFlyPnr(flyPnr);

            flyPassengeDetailsVo.setId(flyPassenge.getId());
            flyPassengeDetailsVo.setCusromerIds(flyPassenge.getCusromerIds());
            flyPassengeDetailsVo.setNumber(flyPassenge.getNumber());
            flyPassengeDetailsVo.setPnrId(flyPassenge.getPnrId());
            flyPassengeDetailsVo.setPassageType(flyPassenge.getPassageType());
            flyPassengeDetailsVo.setAccompany(flyPassenge.getAccompany());
            flyPassengeDetailsVo.setMoblePhone(flyPassenge.getMoblePhone());
            flyPassengeDetailsVo.setName(flyPassenge.getName());
            flyPassengeDetailsVo.setCardType(flyPassenge.getCardType());
            flyPassengeDetailsVo.setCardNo(flyPassenge.getCardNo());
            flyPassengeDetailsVo.setIsFlightsms(flyPassenge.getIsFlightsms());
            flyPassengeDetailsVo.setOrderBy(flyPassenge.getOrderBy());
            flyPassengeDetailsVo.setSetDate(flyPassenge.getSetDate());
            flyPassengeDetailsVo.setUpdateDate(flyPassenge.getUpdateDate());
            flyPassengeDetailsVo.setCateror(flyPassenge.getCateror());
            flyPassengeDetailsVo.setCode(flyPassenge.getCode());
            flyPassengeDetailsVo.setInsure(flyPassenge.getInsure());
            flyPassengeDetailsVo.setPassgeBirth(flyPassenge.getPassgeBirth());
            flyPassengeDetailsVo.setXingE(flyPassenge.getXingE());
            flyPassengeDetailsVo.setMingE(flyPassenge.getMingE());
            flyPassengeDetailsVo.setUserId(flyPassenge.getUserId());

            flyPassengerSegmentList = flyPassengerSegmentMapper.selectByOrderIdAndPassengerId(order_id, flyPassenge.getId());
            flyPassengeDetailsVo.setFlyPassengerSegments(flyPassengerSegmentList);

            flyPassengeDetailsVoList.add(flyPassengeDetailsVo);

        }

        return flyPassengeDetailsVoList;
    }

    private List<Payment> getPayment(String orderId) {

        List<Payment> paymentList = new ArrayList<Payment>();
        //根据订单id查询订单支付信息
        List<FlyOrderPayment> flyOrderPaymentList = flyOrderPaymentMapper.selectByOrderNo(orderId);
        if (flyOrderPaymentList != null&&flyOrderPaymentList.size()>0) {
             for (FlyOrderPayment flyOrderPayment:flyOrderPaymentList){
                 Payment payment = paymentMapper.selectByPrimaryKey(flyOrderPayment.getPaymentId());
                 paymentList.add(payment);
             }
        }
        return paymentList;
    }

    /**
     * @return com.myway.dto.common.JsonData
     * @Author MaShuai
     * @Description 根据城市三字码获取城市信息
     * @Date 2018/8/21 18:28
     * @Param [citySZM]
     **/
    @Override
    public JsonData selectTabCityByCitySZM(String citySZM) {
        if (citySZM != null && citySZM != "") {
            TabCity tabCity = tabCityMapper.selectByCitySZM(citySZM);
            return JsonData.success(tabCity);
        } else {
            return JsonData.fail("城市信息查询失败，城市三字码不得为空！");
        }

    }

    /**
     * @return com.myway.dto.common.JsonData
     * @Author MaShuai
     * @Description 根据机场三字码查询机场信息
     * @Date 2018/8/31 11:28
     * @Param [airportSZM]
     **/
    @Override
    public JsonData selectTabAirportManageByAirportNum(String airportNum) {
        if (airportNum != null && airportNum != "") {
            TabAirportManage tabAirportManage = tabAirportManageMapper.selectByAirportNum(airportNum);
            return JsonData.success(tabAirportManage);
        } else {
            return JsonData.fail("机场信息查询失败，机场三字码不得为空！");
        }
    }

    /**
     * @return com.myway.dto.common.JsonData
     * @Author MaShuai
     * @Description 根据订单号查询航段信息
     * @Date 2018/8/21 18:38
     * @Param [OrderId]
     **/
    @Override
    public JsonData selectFlySegmentByOrderId(String orderId) {
        if (orderId != null && orderId != "") {
            List<FlySegmentVo> flySegments = flySegmentMapper.getFlySegmentByOrderId(orderId);
            return JsonData.success(flySegments);
        } else {
            return JsonData.fail("航段信息查询失败，订单号不得为空！");
        }
    }

    /**
     * 根据订单号查询乘客信息
     *
     * @param orderId
     * @return
     */
    @Override
    public JsonData selectFlyPassengeByOrderId(String orderId) {
        if (orderId != null && orderId != "") {
            List<FlyPassenge> FlyPassengeList = flyPassengeMapper.getFlyPassengeByOrderId(orderId);
            return JsonData.success(FlyPassengeList);
        } else {
            return JsonData.fail("航段信息查询失败，订单号不得为空！");
        }


    }

    @Override
    public JsonData findAllPnrByOrderID(String orderId) {
        if (orderId != null && orderId != "") {
            List<FlyPnr> flyPnrList = flyPnrMapper.getPnrOrderId(orderId);
            return JsonData.success(flyPnrList);
        }
        return JsonData.fail("航段信息查询失败，订单号不得为空！");
    }


    @Override
    @Transactional
    public void handleInPaymentOrder() {
        log.info("====@@@@========》》》开始处理订单中的支付中的超过十分钟的订单============");
        try {
            List<FlyOrder> orderList = flyOrderMapper.handleInPaymentOrder();
            for (FlyOrder order : orderList) {
                String firstTransId = order.getFirstTransId();
                Long orderId = order.getId();
                if (StringUtils.isEmpty(firstTransId)) {
                    log.info("====@@@@=====》》》订单id是" + order.getId() + " 这个订单没有firstTransId");
                    continue;
                }
                String callBackResultStr = tbcPayService.callBackByTransId(firstTransId);
                //如果transId 返回值是null的  证明  transId 的值不是正常的
                //直接改变订单状态
                if(StringUtils.isEmpty(callBackResultStr)){
                    order.setOrderStatus(OrderStatus.PV.toString());
                    order.setUpdateDate(new Date());
                    flyOrderMapper.updateByPrimaryKeySelective(order);
                    continue;
                }
                callBackResultStr = callBackResultStr.replaceAll("(\r\n|\r|\n|\n\r)", "<br>");
                Map<String, String> callBackResultMap = getCallBackResultMap(orderId + "", firstTransId, callBackResultStr);
                if (callBackResultMap == null) continue;
                String result = callBackResultMap.get("RESULT"), result_code = callBackResultMap.get("RESULT_CODE"), DSECURE = callBackResultMap.get("3DSECURE"), RRN = callBackResultMap.get("RRN"), APPROVAL_CODE = callBackResultMap.get("APPROVAL_CODE"), BANK_ID = callBackResultMap.get("CARD_NUMBER");
                String paymentResult = tbcPayService.addTbcPaymentInfo(String.valueOf(orderId), firstTransId, result, result_code, DSECURE, RRN, APPROVAL_CODE, BANK_ID, callBackResultStr, firstTransId, "task");
                if (paymentResult.equals("error")) {
                    System.out.println("=======>>>======@@@@===定時处理支付中时添加支付信息失败  order id=" + orderId);
                }
                if (result != null && result.equals("FAILED")) {
                    //支付失败
                    order.setOrderStatus(OrderStatus.PV.toString());
                } else if (result != null && result.equals("OK")) {
                    List<FlyPnr> flyPnrList = flyPnrMapper.getPnrOrderId(String.valueOf(orderId));
                    boolean ticketFlag = false; //true 已经出票 false 没有出票
                    int ticketNum = 0;//0pnr 无效  1 pnr 有效
                    for (FlyPnr flyPnr : flyPnrList) {
                        //ticket已经出票
                        System.out.println("pnrCommand.isTicket(flyPnr.getPnrNo()===" + pnrCommand.isTicket(flyPnr.getPnrNo()));
                        if (!pnrCommand.isTicket(flyPnr.getPnrNo())) {
                            log.info("====@@@@=====》》》订单id是" + orderId + "  这个订单已经支付已经出票PnrNo 是=" + flyPnr.getPnrNo());
                            ticketFlag = true;
                        } else if (pnrCommand.pnrExist(flyPnr.getPnrNo()) && pnrCommand.isTicket(flyPnr.getPnrNo())) {
                            //pnr 有效   ticket 没有出票
                            log.info("====@@@@=====》》》订单id是" + orderId + "  这个订单已经支付没有出票PnrNo有效 pnr是=" + flyPnr.getPnrNo());
                            ticketFlag = false;
                            ticketNum = 1;
                            break;
                        } else {
                            log.info("====@@@@=====》》》订单id是" + orderId + "  这个订单已经支付没有出票PnrNo无效 pnr是=" + flyPnr.getPnrNo());
                            ticketFlag = false;
                            ticketNum = 0;
                        }
                    }

                    String contexts = "hello(您好)+ <br/><br/>&nbsp;&nbsp;&nbsp;&nbsp;这个订单是" + orderId + "已经支付成功 但没有出票 transId是=" + firstTransId + "请及时处理";
                    if (ticketFlag) {
                        order.setOrderStatus(OrderStatus.PF.toString());
                    } else {
                        if (ticketNum == 1) {
                            JsonData jsonData = ticketService.handleTicket(order.getOrderId());
                            if (jsonData.isRet()) {
                                order.setOrderStatus(OrderStatus.PF.toString());
                                TabMembIntegral tabMembIntegral = new TabMembIntegral();
                                Map map = new HashMap();
                                map.put("type","memb_id");
                                map.put("value",order.getUserId());
                                TabMemberInfo member = myTabMemberInfoMapper.selectMemb2(map).get(0);
                                if(StringUtils.isBlank(member.getMembRegisterType()) || !member.getMembRegisterType().equals("1")) {
                                    tabMembIntegral.setMembId(member.getMembId());
                                    tabMembIntegral.setMembLoginName(member.getMembEnSurname() + member.getMembEnName());
                                    integralService.distanceToIntegral(tabMembIntegral, String.valueOf(orderId));
                                }
                            } else {
                                EmailUtils.sendHtmlEmail("yangyuezhang@qmiyun.cn", "MyWay 已支付未出票", contexts, "");
                                order.setOrderStatus(OrderStatus.HP.toString());
                            }
                        } else {
                            EmailUtils.sendHtmlEmail("yangyuezhang@qmiyun.cn", "MyWay 已支付未出票", contexts, "");
                            order.setOrderStatus(OrderStatus.HP.toString());
                        }
                    }
                } else {
                    //出票失败
                    order.setOrderStatus(OrderStatus.PV.toString());
                }
                order.setUpdateDate(new Date());
                FlyOrder flyOrder = flyOrderMapper.selectByPrimaryKey(orderId);
                if (flyOrder != null && !flyOrder.getFirstTransId().equals(firstTransId)) {
                    continue;
                }
                flyOrderMapper.updateByPrimaryKeySelective(order);
            }
            log.info("====@@@@========》》》订单中的支付中的超过十分钟的订单处理结束============");
        } catch (Exception e) {
            log.info("====@@@@===处理订单发现异常");
            e.printStackTrace();
        }
    }

    @Override
    public JsonData getPassengerAndSegmentAndOrderInfoByOrderId(String orderId) {
        if(StringUtils.isEmpty(orderId)){
            return  JsonData.fail("order id not can is null");
        }
        Map<String,Object>  resultMap=new HashMap<String,Object>();
        FlyOrder flyOrder = flyOrderMapper.selectByPrimaryKey(Long.parseLong(orderId));
        if(flyOrder==null){
            return  JsonData.fail("No order information was queried");
        }
        resultMap.put("flyOrder",flyOrder);
        List<FlyPassenge> FlyPassengeList = flyPassengeMapper.getFlyPassengeByOrderId(orderId);
        List<FlySegmentVo> FlySegmentVoList = flySegmentMapper.getFlySegmentByOrderId(orderId);
        resultMap.put("flyPassengeList",FlyPassengeList);
        resultMap.put("flySegmentVoList",FlySegmentVoList);
        return   JsonData.success(resultMap,"The query is successful");
    }

    @Override
    public ResultEntity getOrderPayInfo(String orderId) {
        if(StringUtils.isEmpty(orderId)){
            return ResultEntity.fail("Order id is not null");
        }
        FlyOrder flyOrder = flyOrderMapper.selectByPrimaryKey(Long.parseLong(orderId));
        if(flyOrder==null || StringUtils.isEmpty(flyOrder.getFirstTransId())){
            return ResultEntity.fail("No order found or Not paying");
        }
        String callBackResultStr= tbcPayService.callBackByTransId(flyOrder.getFirstTransId());
        Map<String, String> parsingCallBackMap = tbcPayService.getParsingCallBackMap(callBackResultStr);
        if(parsingCallBackMap==null){
            log.info("===========@@@@====FlyaymentController TBCOKCallBack=======>>>======@@@@===支付返回的信息是error信息");
            return ResultEntity.fail("pay info return null");
        }
        String result = parsingCallBackMap.get("RESULT"), result_code = parsingCallBackMap.get("RESULT_CODE"), DSECURE = parsingCallBackMap.get("3DSECURE"), RRN = parsingCallBackMap.get("RRN"), APPROVAL_CODE = parsingCallBackMap.get("APPROVAL_CODE"), BANK_ID = parsingCallBackMap.get("CARD_NUMBER");
        if(result != null && result.equals("OK"))  return ResultEntity.success("Pay for success");
        if(flyOrder.getOrderStatus()!=null&&flyOrder.getOrderStatus().equals(OrderStatus.PI.toString())){
            String paymentResult = tbcPayService.addTbcPaymentInfo(orderId, flyOrder.getFirstTransId(), result, result_code, DSECURE, RRN, APPROVAL_CODE, BANK_ID, callBackResultStr, flyOrder.getFirstTransId(), "");
            if (paymentResult.equals("error")) {
                log.info("FlyaymentController TBCOKCallBack=======>>>======@@@@===添加支付信息失败");
            }
            flyOrder.setOrderStatus(OrderStatus.PV.toString());
            updateByPrimaryKeySelective(flyOrder);
        }
         return ResultEntity.fail("Pay for failure");
    }

    //获取根据transid获取的支付返回信息
    public static Map<String, String> getCallBackResultMap(String orderId, String firstTransId, String callBackResultStr) {
        //当返回 ERROR 直接返回
        Map<String, String> callBackMap = new HashMap<String, String>();
        if (StringUtils.isEmpty(callBackResultStr)) {
            return null;
        }
        String[] resultError = callBackResultStr.split(":");
        String s1 = resultError[0];
        if (callBackResultStr == null || s1.equals("ERROR")) {
            log.info("====@@@======》》》处理订单中的订单orderId是=" + orderId + " firstTransId是" + firstTransId);
            return null;
        }
        String[] data1 = callBackResultStr.split("<br>");
        if (data1 != null && data1.length > 0) {
            for (String s : data1) {
                String[] data2 = s.split(":");
                if (data2 != null && data2.length > 0)
                    callBackMap.put(data2[0].trim(), data2[1].trim());
            }
        }
        return callBackMap;
    }

    @Override
    public JsonData refundApply(String orderId,String option,String reason){
        if(StringUtils.isNotBlank(orderId)){
            FlyRefundReversal flyRefundReversal = new FlyRefundReversal();
            flyRefundReversal.setOrderId(Long.valueOf(orderId));
            flyRefundReversal.setRequestOption(option);
            flyRefundReversal.setRequestReason(reason);
            flyRefundReversal.setRequestTime(new Date());
            int i = flyRefundReversalMapper.insert(flyRefundReversal);
            FlyOrder flyOrder = flyOrderMapper.selectByPrimaryKey(Long.valueOf(orderId));
            if(!flyOrder.getOrderStatus().equals(OrderStatus.PF.toString()))
                return JsonData.fail("Application for refund failed.");
            FlyOrder update = new FlyOrder();
            update.setId(flyOrder.getId());
            update.setOrderStatus(OrderStatus.RI.toString());
            i += flyOrderMapper.updateByPrimaryKeySelective(update);
            if(i == 2)
                return JsonData.success(null,"Successful application for refund.");
            return JsonData.fail("Application for refund failed.");
        }else{
            return JsonData.fail("Order operation failed, order number shall not be empty!");
        }
    }

    @Override
    public JsonData refundOptions() {
        return JsonData.success(flyRefundOptionMapper.findAll());
    }
}
